package com.cjx.learn.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
* rabbitmq配置
* @author cjunxian
* @date 2021/9/3
*/
@Slf4j
@Configuration(value = MqConfig.BEAN_NAME)
public class MqConfig {

    public static final String BEAN_NAME = "mqconfig";

    private final String QUEUE_PREFIX = "webmq:queue:";

    @Autowired
    Environment environment;

    /**
     * 获取端口
     * @return 本机端口号
     */
    private String getPort(){
        return environment.getProperty("server.port");
    }

    /**
     * 获取ip
     * @return 本机ip
     */
    private String getIp(){
        InetAddress localHost = null;
        try {
            localHost = Inet4Address.getLocalHost();
        } catch (UnknownHostException e) {
            log.error(e.getMessage(),e);
        }
        return localHost.getHostAddress();
    }

    /**
     * 获取队列名称
     * @return 队列名称
     */
    public String getQueueName(){
       return QUEUE_PREFIX + getIp() + ":" + getPort();
    }

    /**
     * 注册本机的队列
     * @return
     */
    @Bean("#{mqconfig.getQueueName()}")
    public Queue queue(){
        return new Queue(getQueueName(),true,false,false);
    }

}
